/**
 * 
 */
package it.unitn.testbed.server.config;

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;

/**
 * This servlet handles the upload of a new XML configuration of the testbed.
 * 
 * Objects interested in receiving notifications of configurations changes
 * events must implement {@link ConfigUser} and register using
 * {@link #registerService(ConfigUser)}. Note that the registration
 * function and the associated state are static, which means that all producers
 * of configuration change events are going to notify all users.
 * 
 * @author Stefan Guna
 * 
 */
public class ConfigUpload extends UploadAction {

	public static Logger log = Logger.getLogger(ConfigUpload.class.getName());
	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 * 
	 * @seegwtupload.server.UploadAction#executeAction(javax.servlet.http.
	 * HttpServletRequest, java.util.List)
	 */
	@Override
	public String executeAction(HttpServletRequest request,
			List<FileItem> sessionFiles) throws UploadActionException {
		TestbedConfig testbedConfig;
		for (FileItem item : sessionFiles) {
			if (item.isFormField() == true)
				continue;
			try {
				testbedConfig = new TestbedConfig(item
						.getInputStream());

				for (ConfigUser configUser : TestbedConfig
						.getConfigurationUsers())
					configUser.setConfig(testbedConfig);
			} catch (Exception e) {
				log.trace("Throwing exception: " + e.getMessage());
				throw new UploadActionException(e.getMessage());
			}
		}
		removeSessionFileItems(request);
		return "Successfully updated deployment.";
	}
}
